package org.darkforest.controller;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import org.darkforest.auth.AuthPassport;
import org.darkforest.auth.CurrentMember;
import org.darkforest.common.services.SettingService;
import org.darkforest.common.services.WxJSSdkService;
import org.darkforest.common.util.AliOssFileUploadUtil;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.wxpay.payutils.Sha1Util;
import org.darkforest.enums.SettingNameEnum;
import org.darkforest.model.Member;
import org.darkforest.model.RestEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 其他信息接口
 *
 * @auth bingo
 * @create 2017-12-11-16:53
 */
@RestController
@RequestMapping(value = "other")
@Api(value = "other", description = "其他信息接口", produces = MediaType.APPLICATION_JSON_VALUE)
public class OtherController {


    @Autowired
    private SettingService settingService;

    @Autowired
    private WxJSSdkService wxJSSdkService;


    @RequestMapping(value = "getServerDatetime")
    @ApiOperation(value = "获取服务器当前时间", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity getServerDatetime() {
        return RestEntity.success(DateUtil.unixTimeStampInt().intValue());
    }


    /**
     * 获取微信调用jssdk信息
     *
     * @param url 使用jsskd访问url
     * @return
     */
    @RequestMapping(value = "getWxAccess", method = RequestMethod.GET)
//    @AuthPassport
    @ApiOperation(value = "获取微信授权", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity getWxAccess(String url, String inMode) {
        Map<String, String> result = new HashMap<String, String>();
        String nonceStr = Sha1Util.getNonceStr();//随机字符串
        String timeStamp = Sha1Util.getTimeStamp();//时间戳
        String appId = settingService.getSettingInfo(SettingNameEnum.WXPAY_APP_ID);
        String signature;
        try {
            signature = wxJSSdkService.getJsSignature(nonceStr, url, timeStamp, inMode);
            result.put("nonceStr", nonceStr);
            result.put("timeStamp", timeStamp);
            result.put("appId", appId);
            result.put("signature", signature);
            return RestEntity.success(result);

        } catch (Exception e) {
            e.printStackTrace();
            return RestEntity.failed("签名失败");
        }
    }

    /**
     * 图片上传，返回保存成功的对象
     *
     * @return
     */
    @AuthPassport
    @RequestMapping(value = "uploadPic", method = RequestMethod.POST)
    @ApiOperation(value = "图片上传", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity uploadPic(@CurrentMember Member member, @RequestBody String[] base64Array) {
        try {

            String base64Str = null;

            BASE64Decoder decoder = new BASE64Decoder();
            String imagPath = System.getProperty("user.dir") + System.getProperty("file.separator") ;

            List<String>  picNameList = new ArrayList<String>();

            for (int i = 0; i < base64Array.length; i++) {
                base64Str = base64Array[i];
                System.out.println("base64Str=" + base64Str);
                // 过滤特殊字符
                base64Str = base64Str.trim().replaceAll("%", "").replaceAll(",", "").replaceAll(" ", "+");
                System.out.println("base64Str1=" + base64Str);

                //Base64解码
                byte[] b = decoder.decodeBuffer(base64Str);
                for (int j = 0; j < b.length; ++j) {
                    //调整异常数据
                    if (b[j] < 0) {
                        b[j] += 256;
                    }
                }

                // 新生成的图片
                String imagName = new Date().getTime() + ".jpg";
                String imgFilePath = imagPath + imagName;
                OutputStream out = new FileOutputStream(imgFilePath);
                out.write(b);
                out.flush();
                out.close();
                System.out.println("imgFilePath=" + imgFilePath);

                picNameList.add(imagName);
            }

            for (int i=0; i<picNameList.size(); i++) {
                String imagName = picNameList.get(i);
                File uploadFile = new File(imagPath + imagName);
                AliOssFileUploadUtil.uploadMemberPic(member.getMemberId().toString(), imagName, uploadFile);

                //删除temp下的临时文件
                final String fullname = imagPath + imagName;
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        new File(fullname).delete();
                    }
                }, 60000);
            }

            return RestEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            return RestEntity.failed();
        }
    }
}
